﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Collections;
using System.Threading;

namespace ManagerMachine
{
    public class ManagerProcess
    {
        AllocationPort allocation;
        UpdateXML update_xml;
        CONFIG config;       
        Hashtable Process_Table;
        Hashtable ManagerPort;
        public ManagerProcess(CONFIG config)
        {
            this.config = config;
            allocation = new AllocationPort(config.RANGE_PORT_TABLE.MIN, config.RANGE_PORT_TABLE.MAX);
            update_xml = new UpdateXML();
            Process_Table = new Hashtable();
            ManagerPort = new Hashtable();
        }
        public int StartNewTable(int TableID)
        {
            int newport = allocation.GetNewPort();
            update_xml.ModifyNewPort(TableID,newport,@config.PATH_TABLE_SERVER_CONFIG);           
            ProcessStartInfo info = new ProcessStartInfo(@config.PATH_TABLE_SERVER_EXE);
            //info.WindowStyle = ProcessWindowStyle.Hidden;
            info.ErrorDialog = true;
            info.Arguments = config.PATH_TABLE_SERVER_CONFIG;
            Process process = new Process();
            
            process.StartInfo = info;
            Process_Table.Add(TableID, process);
           // process.Start();            
            Console.WriteLine("Start New Table at Port= " + newport.ToString());
            ManagerPort.Add(TableID, newport);
            Thread.Sleep(300);
            return newport;
        }
        public bool StopTable(int TableID)
        {
            if(Process_Table.ContainsKey(TableID))
            {
                try
                {
                    Process p = (Process)Process_Table[TableID];
                    p.Kill();
                    Process_Table.Remove(TableID);
                    ManagerPort.Remove(TableID);
                }
                catch(Exception e)
                {
                    Console.WriteLine("Process is Stopped!");
                }
                return true;
            }
            return false;
        }
        public int GetPort(int TableID)
        {
            return (int)ManagerPort[TableID];
        }
        public void KillAll()
        {
            foreach (Process obj in Process_Table.Values)
            {
                obj.Kill();
            }
        }
    }
}
